package com.jhh.pay.center.service.impl;

import com.jhh.pay.center.cfg.caching.Cache;
import com.jhh.pay.center.dao.AppMapper;
import com.jhh.pay.center.model.App;
import com.jhh.pay.center.service.AppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author tangxd
 * @Description: TODO
 * @date 2017/12/5
 */
@Service
@Slf4j
public class AppServiceImpl implements AppService {

    @Autowired
    private AppMapper appMapper;

    @Autowired
    private Cache cache;

    private String cacheKey(int appId) {
        return String.format("jhh:pay:app:%d", appId);
    }

    @Override
    public boolean save(App app) {
        app.setPostTime(new Date());
        String secret = UUID.randomUUID().toString().replace("-", "").substring(0, 20);
        app.setSecret(secret);
        long c = appMapper.insert(app);
        if (c > 0) {
            cache.set(cacheKey(app.getId()), app, TimeUnit.SECONDS.convert(3, TimeUnit.DAYS));
        }
        return c > 0;
    }

    @Override
    public boolean update(App app) {
        boolean ok = appMapper.update(app) > 0;
        if (ok) {
            cache.set(cacheKey(app.getId()), app, TimeUnit.SECONDS.convert(3, TimeUnit.DAYS));
        }
        return ok;
    }

    @Override
    public App get(int appId) {
        App app = cache.get(cacheKey(appId), App.class);
        if (null == app) {
            app = appMapper.get(appId);
            if (null != app) {
                cache.set(cacheKey(app.getId()), app, TimeUnit.SECONDS.convert(3, TimeUnit.DAYS));
            }
        }
        return app;
    }

    @Override
    public Collection<App> gets() {
        Collection<Integer> ids = appMapper.gets();
        List<String> cacheKeys = new ArrayList<>();
        for (Integer id : ids) {
            cacheKeys.add(cacheKey(id));
        }
        return cache.gets(cacheKeys, App.class);
    }
}
